<?php
declare (strict_types = 1);

namespace app\auth\controller;

use app\auth\common\util\ApiUtil;
use app\auth\model\AdminModel;
use app\auth\service\AdminService;
use app\auth\service\DeptService;
use app\auth\service\RightService;
use app\auth\service\RoleRightLinkService;
use app\auth\service\RoleService;
use app\auth\service\UserService;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Validate;

class AdminController
{
    public function __construct(AdminService $adminService,
                                DeptService $deptService,
                                RoleService $roleService,
                                UserService $userService,
                                RightService $rightService,
                                RoleRightLinkService $roleRightLinkService)
    {
        $this->adminService = $adminService;
        $this->deptService = $deptService;
        $this->roleService = $roleService;
        $this->userService = $userService;
        $this->rightService = $rightService;
        $this->roleRightLinkService = $roleRightLinkService;
    }

    // 管理员列表
    public function list(){
        $where = $limit = $sort = array();
        $params = request()->param();
        if ($params['username']){ //根据用户名模糊查询
            $users = $this->userService->select([['username', 'like', '%'.$params['username'].'%']],'id');
            $user_ids = [];
            foreach ($users as $user) $user_ids[] = $user['id'];
            $where['user_ids'] = $user_ids;
        }
        $limit['page'] = !empty($params['page'])?intval($params['page']):1;
        $limit['pagesize'] = !empty($params['pagesize'])?intval($params['pagesize']):10;
        $sort = !empty($params['sort'])?explode(',', $params['sort']):[];
        $list = $this->adminService->list($where, $limit, $sort);
        $total = $this->adminService->count($where);
        return ApiUtil::normal(['total'=>$total,'list'=>$list]);
    }

    public function add()
    {
        $user_model = $this->userService->model();
        $params = request()->param();
        $validate = Validate::rule([
            'dept_id'=>'require',
            'role_id' => 'require',
            'username' => 'require|unique:'.$user_model->getTable(),
            'password' => 'require',
            'type' => 'require',
            'status' => 'require',
        ]);
        if(!$validate->check($params)) return ApiUtil::normal(null, $validate->getError(), ApiUtil::CODE_FAIL);
        DB::startTrans();
        try{
            !$this->deptService->count(['id'=>$params['dept_id']]) && ApiUtil::abort('不存在部门');
            !$this->roleService->count(['id'=>$params['role_id']]) && ApiUtil::abort('不存在角色');
            $user_data = $admin_data = array();
            $user_data['username'] = $params['username'];
            $user_data['realname'] = $params['realname']??0;
            $user_data['password'] = $user_model::passwordEncode($params['password']);
            $user_data['gender'] = $params['gender']??0;
            $user_data['phone'] = $params['phone']??0;
            $user_data['status'] = 1;
            $user_data['email'] = $params['email']??'';
            $user_data['reg_time'] = time();
            $user_data['last_time'] = 0;
            $user_data['last_ip'] = 0;
            $user_data['login_times'] = 0;
            $user_data['reg_ip'] = request()->ip();
            $user_last_id = $this->userService->insertGetId($user_data);
            if(empty($user_last_id)) ApiUtil::abort('创建用户失败');
            $admin_data['dept_id'] = $params['dept_id'];
            $admin_data['role_id'] = $params['role_id'];
            $admin_data['type'] = $params['type'];
            $admin_data['remark'] = $params['remark']??'';
            $admin_data['status'] = $params['status'];
            $admin_data['deadline'] = 0;
            $admin_data['user_id'] = $user_last_id;
            $admin_last_id = $this->adminService->insertGetId($admin_data);
            if(empty($admin_last_id)) ApiUtil::abort('创建员工失败');
            DB::commit();
            return ApiUtil::normal( ['id'=>$admin_last_id]);
        }catch (\Exception $e){
            DB::rollBack();
            return ApiUtil::excep($e);
        }
    }

    public function update(){
        $user_model = $this->userService->model();
        $params = request()->param();
        $id = $params['id']??0;
        if(empty($id)) return ApiUtil::normal(null, '请输入员工ID', ApiUtil::CODE_FAIL);
        DB::startTrans();
        try{
            if(!empty($params['dept_id'])) !$this->deptService->count(['id'=>$params['dept_id']]) && ApiUtil::abort('不存在部门');
            if(!empty($params['role_id'])) !$this->roleService->count(['id'=>$params['role_id']]) && ApiUtil::abort('不存在角色');
            $old_admin = $this->adminService->find(['id'=>$id]);
            empty($old_admin) && ApiUtil::abort('不存在员工');
            $old_user = $this->userService->find(['id'=>$old_admin['user_id']]);
            empty($old_user) && ApiUtil::abort( '不存在用户');
            $userData = $adminData = array();
            if (!empty($params['username'])){
                $uniqueUsername = $this->userService->count([['username','=',$params['username']],['id','<>',$old_admin['user_id']]]);
                if($uniqueUsername) ApiUtil::abort('用户名已存在');
                $userData['username'] = $params['username'];
            }
            if (!empty($params['realname'])) $userData['realname'] = $params['realname'];
            if (!empty($params['password'])) $userData['password'] = $user_model::passwordEncode($params['password']);
            if ($params['gender']!= null) $userData['gender'] = $params['gender'];
            if (!empty($params['phone'])) $userData['phone'] = $params['phone'];
            if (!empty($params['email'])) $userData['email'] = $params['email'];
            if (!empty($params['role_id'])) $update = $this->userService->update(['id'=>$old_admin['user_id']],$userData);
            if(!$update && $update!=0) ApiUtil::abort('修改用户失败');
            if (!empty($params['dept_id'])) $adminData['dept_id'] = $params['dept_id'];
            if (!empty($params['role_id'])) $adminData['role_id'] = $params['role_id'];
            if (!empty($params['type'])) $adminData['type'] = $params['type'];
            if (!empty($params['remark'])) $adminData['remark'] = $params['remark'];
            if ($params['status'] != null) $adminData['status'] = $params['status'];
            $this->adminService->update(['id'=>$id],$adminData);
            DB::commit();
            return ApiUtil::normal( ['id'=>$id]);
        }catch (\Exception $e){
            DB::rollBack();
            return ApiUtil::excep($e);
        }
    }

    // 筛选配置
    public function opt(){
        //部门选项
        $dept_list = $this->deptService->list();
        return ApiUtil::normal( [
            'dept_list' => $dept_list,
            'type_map' => $this->adminService->model()::$TYPE_STR,
            'status_map' => $this->userService->model()::$STATUS_STR,
            'gender_map' => $this->userService->model()::$GENDER_STR,
        ]);
    }


    public function login(){
        $params = request()->param();
        $validate = Validate::rule([
            'username'=>'require',
            'password' => 'require'
        ]);
        if(!$validate->check($params)) return ApiUtil::normal(null, $validate->getError(), ApiUtil::CODE_FAIL);
        //登陆并获取用户信息及token
        DB::startTrans();
        try{
            //获取用户信息
            $user_info = $this->userService->userInfo($params['username'], $params['password']);
            $profile = [
                'username' => $user_info['username'],
                'realname' => $user_info['realname'],
                'last_ip' => $user_info['last_ip'],
                'last_time' => $user_info['last_time'],
                'last_time_str' => $user_info['last_time_str'],
                'reg_time' => $user_info['reg_time'],
                'reg_time_str' => $user_info['reg_time_str'],
            ];
            //获取管理员信息
            $admin_info = $this->adminService->find(['user_id'=>$user_info['id']]);
            empty($admin_info) && ApiUtil::abort( '你不是管理员');
            if($admin_info['status']!=1) ApiUtil::abort('员工未激活');
            $profile['role'] = $admin_info['role'];
            $profile['dept'] = $admin_info['dept'];
            $profile['type'] = $admin_info['type'];
            $profile['type_str'] = $admin_info['type_str'];
            //获取管理员权限
            $rights = [];
            if ($admin_info['type'] == AdminModel::TYPE_SUPER){
                $rights_t = $this->rightService->select([['pid', '>', 0]],['id']);
                foreach ($rights_t as $right) $rights[] = $right['id'];
            }else{
                $rights_t = $this->roleRightLinkService->select(['role_id'=>$admin_info['role_id']],['right_id']);
                foreach ($rights_t as $right) $rights[] = $right['right_id'];
            }
            //获取权限表
            $right_tree = $this->rightService->rightTree();
            //获取管理员的按钮
            $btns = $this->rightService->rightTreeFilter($right_tree, $rights, $this->rightService->model()::TYPE_BTN);
            //获取管理员的菜单
            $menus = $this->rightService->rightTreeFilter($right_tree, $rights, $this->rightService->model()::TYPE_MENU);
            //设置token
            $token_info = $this->adminService->setLoginToken($user_info['id']);
            !$token_info && ApiUtil::abort('缓存登陆信息失败');
            DB::commit();
            //返回token和用户信息
            return ApiUtil::normal([
                'token' => $token_info['token'],
                'expires' => $token_info['expires'],
                'profile' => $profile,
                'menu' => $menus,
                'btn' => $btns,
            ]);
        }catch (\Exception $e){
            DB::rollBack();
            return ApiUtil::excep($e);
        }

    }
}
